﻿using UnityEngine;

/// <summary>
/// move back and forth between several points
/// </summary>
public class MovePathObj : MonoBehaviour
{
    int m_Index;

    public Transform pointsParent;

    Transform[] points;

    public bool focusDir = true;

    private void Start()
    {
        pointsParent.SetParent(transform.parent);
        points = new Transform[pointsParent.childCount];

        for (int i = 0; i < pointsParent.childCount; i++)
        {
            points[i] = pointsParent.GetChild(i);
        }
    }

    public float moveSpeed = 1;
    Vector3 GetCurTargetPos()
    {
        if(m_Index >= points.Length)return Vector3.zero;

        return points[m_Index].position;
    }

    bool ArrivedAt(Vector3 pos)
    {
        return (transform.position - pos).magnitude < 0.2f;
    }

   
    // Update is called once per frame
    void Update()
    {
        var target = GetCurTargetPos();

        if (ArrivedAt(target))
        {
            //GameDebug.Log($"arrived at :{target}");
            m_Index++;
            m_Index %= points.Length;
            target = GetCurTargetPos();
        }
        var dir = target - transform.position;

        var pos = transform.position + Time.deltaTime * moveSpeed * dir.normalized;

        transform.position = pos;

        if (focusDir)
        {
            Vector2 dir2D = new Vector2(dir.x, dir.z);

            if (dir2D.sqrMagnitude > 0)
            {
                Quaternion targetRotation = Quaternion.Euler(0, RoleEntity.DirToRotateAngle(dir2D), 0);
                //this.transform.localRotation = Quaternion.Lerp(this.transform.localRotation, targetRotation,
                //    Time.deltaTime * 30);
            }
        }
        
    }
}